<template>
  <div class="notice">
    <div class="search d-between">
      <div class="d-start">
        <div class="d-center" style="margin-right:10px;">
          <el-button
            size="medium"
            type="info"
            @click="getPageData()"
            icon="el-icon-refresh"
            style="width:36px;height:36px;padding:0;"
          ></el-button>
          <el-button size="medium" type="primary" @click="add()">新增</el-button>
        </div>
        <div class="d-center" style="margin-right:10px;">
          <el-button size="medium" :type="selectData.length>0?'danger':'info'" @click="del()">删除</el-button>
        </div>
      </div>
      <div class="d-end">
        <div class="input d-center">
          <el-input size="medium" v-model="title" placeholder="请输入标题">
            <template slot="prepend">检索:</template>
          </el-input>
        </div>
        <!-- <div class="input d-center">
        <span>项目：</span>
        <el-select size="medium" v-model="active" placeholder="请选择">
          <el-option value="1">新建</el-option>
        </el-select>
        </div>-->
        <div class="d-center" style="margin-left:10px;">
          <el-button size="medium" type="info" plain @click="getPageData">搜索</el-button>
          <!-- icon="el-icon-search"
          style="width:36px;height:36px;padding:0;"-->
          <el-button size="medium" type="info" @click="title='';getPageData()" plain>重置</el-button>
        </div>
      </div>
    </div>
    <div class="main">
      <el-table
        :data="tableData"
        style="width: 100%;"
        height="90%"
        @selection-change="handleSelectionChange"
        v-loading="isLoading"
        ref="multipleTable"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="序号" align="center" width="50">
          <template slot-scope="scope">
            <!-- <span>{{scope.$index + 1}}</span> -->
            <span>{{(scope.$index + 1)+((page-1)*pageSize)}}</span>
          </template>
        </el-table-column>

        <el-table-column prop="title" label="公告标题" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>
              <!-- <sup v-if="scope.row.is_read == 0"></sup> -->
              <el-link
                type="primary"
                @click="view(scope.row),contentDetail=scope.row;dialogFormVisible2=true"
              >{{scope.row.title}}</el-link>
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="user" label="创建人" align="center"></el-table-column>
        <el-table-column prop="create_time" label="创建时间" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="is_top" label="置顶" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_top"
              :active-value="2"
              :inactive-value="1"
              @change="change(scope.$index,scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" align="center">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              v-model="scope.row.sort"
              @change="inputchange(scope.$index,scope.row)"
              :min="0"
              :max="100000"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200" align="center">
          <template slot-scope="scope">
            <!-- <el-button
              size="medium"
              type="success"
              plain
              @click="view(scope.row),contentDetail=scope.row;dialogFormVisible2=true"
            >查看</el-button>-->
            <el-button size="medium" type="primary" plain @click="edit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        layout="prev, pager, next"
        @current-change="pageChange"
        :page-size="pageSize"
        :total="total"
        class="d-center"
        style="padding:10px 0"
      ></el-pagination>
    </div>

    <el-dialog
      title="通知公告"
      :visible.sync="dialogFormVisible"
      @close="close"
      width="80%"
      top="10"
      :destroy-on-close="true"
    >
      <el-form :model="form" v-loading="loading" class="contentshow">
        <el-form-item prop="name" label="通知公告标题" :label-width="'100px'">
          <el-input size="medium" v-model.trim="form.title" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item prop="name" label="通知公告内容" :label-width="'100px'">
            <el-upload
            :on-success="handleSuccess"
            :show-upload-list="false"
            :format="['jpg','jpeg','png','gif']"
            :max-size="2048"
            multiple
            action="/api/index/uploads2"
            accept=".jpg, .png, .jpeg"
            >
            <Button icon="ios-cloud-upload-outline" ></Button>
          </el-upload>
          <quillEditor v-model.trim="form.content" :options="opation" ref="QuillEditor"></quillEditor>
        </el-form-item>

        <el-form-item prop="is_top" label="置顶" :label-width="'100px'">
          <el-switch v-model="form.is_top" :active-value="2" :inactive-value="1"></el-switch>
        </el-form-item>
        <el-form-item prop="sort" label="排序" :label-width="'100px'">
          <el-input-number size="small" v-model="form.sort" :min="0" :max="100000"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible=false">取 消</el-button>
        <el-button size="medium" type="primary" @click="save()" :loading="loading">保 存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="公告内容" :visible.sync="dialogFormVisible2" width="80%" top="10">
      <el-form>
        <h2 class="h2">
          <span v-text="contentDetail.title"></span> &nbsp;
          <small v-text="contentDetail.create_time"></small>
        </h2>
        <hr class="hr" />
        <div v-html="contentDetail.content" class="img colora"></div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogFormVisible2=false">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog
      title="公告内容"
      :visible.sync="dialogFormVisible2"
      @close="dialogFormVisible2=false"
      width="80%"
      top="10"
    >
      <h4>公告标题</h4>
      <div v-html="contentDetail.title" style="margin-bottom:20px"></div>
      <h4>公告内容</h4>
      <div v-html="contentDetail.content"></div>
    </el-dialog>-->
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
// import quillConfig from "../../../config/quill-config";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { debounce } from "@/plugins/common.js";

export default {
  components: {
    quillEditor
  },
  name: "notice",
  data() {
    return {
      pageSize: 0, //每页显示多少
      total: 0, //总数
      name: "",
      active: "",
      title: "", //搜索条件
      dialogFormVisible: false, //编辑新增弹窗
      dialogFormVisible2: false, //查看弹窗
      contentDetail: "", //查看弹窗中显示内容
      selectData: [], //表格选中的数据
      tableData: [], //表格数据
      form: null, //表单数据
      page: 1, //当前页码
      isLoading: false, //表格加载动画
      loading: false,
      opation: {
        // placeholder: "请填写描述，字数不超过2000",
         modules: {
          toolbar:{
            handlers: {
              'image': function (value) {
                  if (value) {
                      document.querySelector('.el-upload').click()
                      // alert('自定义图片')
                  } else {
                      this.quill.format('image', false);
                  }
              }
            },
            container: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote", "code-block"],
              [{ header: 1 }, { header: 2 }],
              [{ list: "ordered" }, { list: "bullet" }],
              // [{ script: "sub" }, { script: "super" }],
              // [{ indent: "-1" }, { indent: "+1" }],
              // [{ direction: "rtl" }],
              // [{ size: ["small", false, "large", "huge"] }],
              // [{ header: [1, 2, 3, 4, 5, 6, false] }],
              // [{ color: [] }, { background: [] }],
              // [{ font: [] }],
              // [{ align: [] }],
              // [{ clean: "源码编辑" }],
              ["link", "image"],
              ["sourceEditor"], //新添加的工具
            ],  // 工具栏
          }
        },
      }
    };
  },
  created() {
    this.formInit();
    this.getPageData();
  },
  methods: {
    handleSuccess (res) {
        // 获取富文本组件实例
        let quill = this.$refs.QuillEditor.quill
        // 如果上传成功
        if (res) {
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片，res为服务器返回的图片链接地址
            quill.insertEmbed(length, 'image', res.code)
            // 调整光标到最后
            quill.setSelection(length + 1)
        } else {
            this.$message({
              message: '图片插入失败',
              type: "error",
            });
            // 提示信息，需引入Message
            // Message.error('图片插入失败')
        }
    },
    formInit() {
      this.form = {
        title: "",
        content: "",
        sort: 1
      };
    },
    pageChange(val) {
      this.page = val;
      this.getPageData();
    },
    getPageData() {
      this.isLoading = true;
      this.$get("/api/Engineer/notice", {
        title: this.title,
        page: this.page
      }).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.total;
          this.pageSize = res.data.limit;
        }
        this.$refs.multipleTable.bodyWrapper.scrollTop = 0;
        this.isLoading = false;
      });
    },
    edit(item) {
      this.form = { ...item };
      this.dialogFormVisible = true;
    },
    close() {
      //   this.dialogFormVisible = false;
    },
    handleSelectionChange(value) {
      this.selectData = value;
    },
    save() {
      this.loading = true;
      delete this.form.link;
      delete this.form.user;
      delete this.form.create_time;
      delete this.form.xmmc;
      delete this.form.xm_cn;
      delete this.form.is_read;
      delete this.form.filesarr;
      this.$post("/api/Engineer/notice_actions", this.form).then(res => {
        if (res.code == 200) {
          this.dialogFormVisible = false;
          this.getPageData();
          this.$Bus.$emit("search");
        }
        this.$message({
          message: res.msg,
          type: res.state
        });
        this.loading = false;
        this.$Bus.$emit("refish");
      });
    },
    add() {
      this.dialogFormVisible = true;
      this.formInit();
    },
    del() {
      if (this.selectData && this.selectData.length > 0) {
        this.$confirm(`是否删除这${this.selectData.length}项`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          let reqs = [];
          this.selectData.map(item => {
            reqs.push(
              this.$post("/api/Engineer/notice_deletes", { id: item.id }).then(
                res => {
                  // this.$message({
                  //   message: res.msg,
                  //   type: res.state
                  // });
                  console.log(res.code);
                }
              )
            );
          });
          Promise.all(reqs).then(() => {
            this.getPageData();
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.$Bus.$emit("refish");
          });
        });
      }
    },
    change: debounce(function(index, data) {
      if (data) {
        var params = {
          id: data.id,
          is_top: data.is_top
        };
        this.$post("/api/Engineer/notice_istop", params).then(res => {
          this.$message({
            message: res.msg,
            type: res.state
          });
          this.getPageData();
          this.$Bus.$emit("refish");
        });
      }
    },500),

    inputchange: debounce(function(index, data) {
      if (data) {
        let boolean = new RegExp("^[0-9]*$").test(data.sort);
        if (!boolean) {
          this.$message({
            type: "error",
            message: "请输入正整数或者0"
          });
          this.getPageData();
          return;
        }

        var params = {
          id: data.id,
          sort: data.sort
        };
        this.$post("/api/Engineer/notice_sort", params).then(res => {
          this.$message({
            message: res.msg,
            type: res.state
          });
          this.getPageData();
          this.$Bus.$emit("refish");
        });
      }
    },500),
    view(item) {
      if (!item["is_read"]) {
        this.$post("/api/Engineer/notice_read", { id: item.id }).then(res => {
          if (res.code == 200) {
            item["is_read"] = 1;
          }
        });
      }
    }
  }
};
</script>
<style lang="less">
.el-upload,.el-upload-list{
  display: none !important;
}
.colora a{
  color: #06c;
  text-decoration: underline;
}
sup {
  width: 6px;
  height: 6px;
  display: inline-block;
  background: #f00;
  // position: absolute;
  // right: 5px;
  // top: 11px;
  position: relative;
  top: -5px;
  border-radius: 50%;
}
.ql-editor {
  min-height: 200px;
  max-height: 500px;
}
.el-dialog img{
  max-width: 100%;
}
</style>
<style lang="less" scoped>

.notice {
  width: 100%;
  height: calc(100%);
  background: white;
  border-radius: 5px;
  .search {
    width: 100%;
    height: 60px;
    padding: 10px 5px;
    position: relative;
    .input {
      width: 300px;
      margin-left: 10px;
      span {
        flex-shrink: 0;
      }
    }
  }
  .main {
    //   width: 100%;
    height: calc(100% - 60px);
    // overflow-y: scroll;
    // position: absolute
    border: 1px solid #ebeef5;
  }
}
.img {
  font-size: 14px;
  line-height: 2;
  text-indent: 2em;
}
.h2 {
  text-align: center;
  small {
    font-weight: 400;
    font-size: 12px;
  }
}
.hr {
  margin: 10px 0;
  border: 0;
  border-top: 1px #ddd solid;
}
.img img {
  max-width: 100%;
}

.tit {
  width: 100%;
  height: 64px;
}
.icon-header {
  position: fixed;
  height: 50px;
  top: 0;
  right: 120px;
}
</style>